<template>
  <n-card ref="elementRef" class="adv-load-page"
    v-if="market.marketingTargetType === 'MARKETING_TARGET_TYPE_CONSUMER_PRODUCT' || adv.auth.mode == 'CREATE_CREATIVE'"
    :header-style="{ padding: '10px', background: '#F1F5FF', marginBottom: '10px' }">
    <template #header>
      <div class="flex items-center">
        <n-text style="width: 160px">{{ index }}.落地页选择</n-text>
        <div style="width: calc(100% - 160px)" v-if="adv.auth.mode !== 'CREATE_CREATIVE'">
          <n-tabs v-model:value="currentTabindex" type="card" size="small" tab-style="min-width: 80px;" style=""
            @update:value="changeTab">
            <n-tab-pane v-for="(item, i) in tabList" :key="item.uuid" :tab="item.accountCode || item.name" :name="i">
            </n-tab-pane>
            <template #suffix>
              <n-radio-group v-model:value="type" name="radioValue" @update:value="handleRadio">
                <n-radio-button :value="1">分账户</n-radio-button>
                <n-radio-button :value="2" :disabled="accountList.length == 1 || isH5">全账户相同</n-radio-button>
                <n-radio-button :value="3" :disabled="accountList.length == 1">广告主体</n-radio-button>
              </n-radio-group>
            </template>
          </n-tabs>
        </div>
      </div>
    </template>
    <n-empty description="请先选择创意模版" v-if="!creativor.creativeTemplateId">
    </n-empty>
    <div v-if="getJumpInfoComponent">
      <x-form ref="formRef" label-placement="top" v-model:model="form" label-width="140" :rules="{}"
        :key="currentTabindex">
        <n-form-item label="落地页" path="goal" style="margin-bottom: 10px;" :show-feedback="false">
          {{ getJumpInfoComponent.label }}
        </n-form-item>

        <div v-for="(item, i) in form.info" class="flex items-center">

          <div class="flex-1">
            <!-- 原生页 -->
            <template v-if="getJumpInfoComponent && getJumpInfoComponent.value.page_type === 'PAGE_TYPE_WECHAT_CANVAS'">
              <n-form-item label="推广页" path="page_id" :rule="formRules.page_id">
                <n-select style="max-width: 360px;" @click="getCanvasPageOption" v-model:value="item.value.page_id"
                  filterable placeholder="请选择" :options="optionals[accountCode] || []" :render-label="renderLabel"
                  clearable @update:value="changeValue">
                  <template #action><span class="text-helper">只显示适用于商品推广的原生推广页</span>
                    <span class="ml-5 link-color cursor-pointer font-12" @click="makeH5">去制作推广页</span>
                    <span @click="() => getCanvasPageOption()" class="ml-5 link-color cursor-pointer font-12">刷新</span>
                  </template>
                </n-select>
              </n-form-item>
            </template>
            <!-- 视频号 -->
            <template
              v-if="getJumpInfoComponent && getJumpInfoComponent.value.page_type === 'PAGE_TYPE_WECHAT_CHANNELS_WATCH_LIVE' && adv.auth.mode == 'CREATE_CREATIVE'">
              <n-form-item label="视频号" path="mini_program_id" :rule="{}">
                <n-select style="max-width: 360px;" placeholder="请选择视频号" @click="getWechatChannelOptional"
                  v-model:value="account.wechatChannels.id" filterable :options="optionals[accountCode] || []"
                  clearable>
                </n-select>
              </n-form-item>
            </template>
            <template
              v-if="getJumpInfoComponent && getJumpInfoComponent.value.page_type === 'PAGE_TYPE_WECHAT_MINI_PROGRAM'">
              <n-form-item label="小程序原始ID" path="mini_program_id" :rule="{}">
                <n-input v-model:value="item.value.mini_program_id" :maxlength="60" show-count :count-graphemes="count"
                  @update:value="changeValue"></n-input>
              </n-form-item>
              <n-form-item label="小程序链接" path="mini_program_path" :rule="formRules.mini_program_id">
                <n-input v-model:value="item.value.mini_program_path" @update:value="changeValue"></n-input>
              </n-form-item>
            </template>
            <n-divider></n-divider>
          </div>
          <div>
            <n-icon size="14" v-if="form.info.length > 1" @click="removeGroup(i)" style="margin-left: 10px;">
              <MinusCircleFilled></MinusCircleFilled>
            </n-icon>
          </div>
        </div>
        <div class="mt-10" v-if="creativor.isComponentCreative">
          <n-button style="width: 100%;" dashed @click="addGroup" :disabled="form.info.length >= 3">还可以添加{{ 3 -
            form.info.length }}组</n-button>
        </div>
      </x-form>
    </div>
  </n-card>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, toRefs, h, watch } from 'vue'
import { useStore } from '@/store'
import { count } from '@/utils/text';
import {
  NForm,
  NCard,
  NEmpty,
  NSpace,
  NTabs,
  NButton,
  NTabPane,
  NDivider,
  NFormItem,
  NText,
  NSelect,
  NInput,
  NRadioGroup,
  NRadioButton,
  NImage,
  NIcon,
  useDialog,
  useMessage
} from 'naive-ui'
import { XForm, XButton, XDataTable } from '@/components';
import { getCanvasPage, getWechatChannel } from '@/api/intelligent';
import { MAIN_JUMP_INFO } from '@/store/modules/adv/helper';
import LoadPage from '@/store/modules/adv/loadPage';
import JumpInfo from '@/store/modules/adv/component/mainJumpInfo';
import { MinusCircleFilled } from '@vicons/antd';
defineProps({
  index: {
    type: Number
  }
})

const store = useStore()
const dialog = useDialog()
const message = useMessage()
const accountList = computed(() => {
  return store.state.adv.accounts
});

const optionals = reactive<any>({

})

const account = computed(() => {
  return accountList.value[0];
})
const adv = computed(() => {
  return store.state.adv.modal;
})
const market = computed(() => {
  return store.state.adv.modal.market;
})
const creativor = computed(() => {
  return store.state.adv.modal.creativor;
});

const getJumpInfoComponent = computed(() => {
  return store.state.adv.modal.marketComponents[MAIN_JUMP_INFO]
});

const isH5 = computed(() => {
  return getJumpInfoComponent.value && getJumpInfoComponent.value.value.page_type === 'PAGE_TYPE_WECHAT_CANVAS'
})



const mdmSortAccounts = computed(() => {
  const mdms: any = [];
  accountList.value.map((account: any) => {
    let mdm = mdms.find((mdm: any) => mdm.id === account.mdmName);
    if (!mdm) {
      mdm = {
        id: account.mdmName,
        accounts: [],
        name: account.mdmName
      }
      mdms.push(mdm)
    }
    mdm.accounts.push(account);
  })
  return mdms;
});

const tabList = computed(() => {
  if (type.value === 3) {
    return mdmSortAccounts.value;
  }
  return accountList.value;
})

const form = reactive({
  info: [new JumpInfo({})]
})


function addGroup() {
  const jump_info = new JumpInfo({})
  form.info.push(jump_info);
}

function removeGroup(i) {
  form.info.splice(i, 1)
}


const type = ref(1);


const formRules = reactive({
  page_id: {
    required: true,
    trigger: 'blur',
    validator(_, __) {
      const hasEmpty = accountList.value.find(_ => {
        const jump_info = _.jumpInfo;
        const hasEmpty = jump_info.find((component) => !component.value.page_id);
        return hasEmpty;
      })
      if (hasEmpty) {

        return new Error(`账户${hasEmpty.accountCode}未填写原生推广页!`)
      }
      return true;
    }
  },
  mini_program_id: {
    required: true,
    trigger: 'blur',
    validator(_, __) {
      const hasEmpty = accountList.value.find(_ => {
        const jump_info = _.jumpInfo;
        const hasEmpty = jump_info.find((component) => !(component.value.mini_program_id && component.value.mini_program_path));
        return hasEmpty;
      })
      if (hasEmpty) {
        return new Error(`账户${hasEmpty.accountCode}未填写小程序ID/链接!`);
      }
      return true;
    }
  },

})

// 落地页变化
watch(() => getJumpInfoComponent.value && getJumpInfoComponent.value.value.page_type, (v) => {
  if (v === 'PAGE_TYPE_WECHAT_CHANNELS_WATCH_LIVE') {
    getWechatChannelOptional();
  }

  if (v === 'PAGE_TYPE_WECHAT_CANVAS') {
    getCanvasPageOption();
  }

})


const currentTabindex = ref(0);

function changeTab(i: any) {
  currentTabindex.value = i;
  if (type.value == 3) {
    changeMdm(i);
  } else {
    changeAccount(i)
  }
}


const accountCode = computed(() => {
  const i = currentTabindex.value;
  let account = null;
  if (type.value == 3) {
    const mdm = mdmSortAccounts.value[i];
    account = mdm.accounts[0]
  } else {
    account = accountList.value[i];
  }
  return account ? account.accountCode : null;

})

function changeAccount(i: any) {
  const account = accountList.value[i];

  if (account) {
    form.info = [].concat([], account.jumpInfo as any);
  }
  getCanvasPageOption();
}
function changeMdm(i: any) {
  const mdm = mdmSortAccounts.value[i];
  if (mdm) {
    form.info = mdm.accounts[0].jumpInfo;
  }
  // form.info =

}

function handleRadio() {
  currentTabindex.value = 0;
}
// const pageOptional = ref([]);
const renderLabel = (option: any): any => {

  return h('div', {
    class: 'flex items-center',
    style: {
      padding: '10px 0'
    }
  }, [
    // h(NImage, {
    //   src: option.url,
    //   fit: 'cover',
    //   width: 30
    // }),
    h('span', {
      style: {
        // marginLeft: '4px',
      }
    }, option.description)
  ])

}


async function getWechatChannelOptional() {
  const res = await getWechatChannel({
    accountCode: accountList.value[0].accountCode
  });


  optionals[accountCode.value] = res.data.map(_ => {
    return {
      label: _.wechat_channels_account_name,
      value: _.wechat_channels_account_id
    }
  });

  // pageOptional.value =
}




async function getCanvasPageOption(options = { overrideOption: 0 }) {
  // const account = accountList.value[currentTabindex.value];
  if (optionals[accountCode.value]) return;

  if (!accountCode.value) return;
  if (!isH5.value) return;
  const value = getJumpInfoComponent.value.value;
  const res = await getCanvasPage({
    accountCode: accountCode.value,
    creativeTemplateId: creativor.value.creativeTemplateId,
    siteSet: isH5.value ? 102 : 21,
    overrideOption: value.override_canvas_head_option,
    refresh: 1
  });
  // form.info

  optionals[accountCode.value] = res.data.map(_ => {
    // const page_elements_spec_list = JSON.parse(_.page_elements_spec_list || "[]")
    // const page_elements = page_elements_spec_list[0] || {};

    return {
      ..._,
    }
  })
}


function makeH5() {
  window.open('https://mp.weixin.qq.com/promotion/eqqframe?t=ad_system/common_simple_frame&t1=rdcanvas/canvas_public')
}



function changeValue() {
  if (type.value == 3) {
    const mdm = mdmSortAccounts.value[currentTabindex.value];
    mdm && mdm.accounts.map((account: any) => {
      account.jumpInfo = form.info.map((jump_info: any) => jump_info.clone());
    })
  }
  if (type.value == 1) {
    const account = accountList.value[currentTabindex.value];
    // 更新账号信息
    if (account) {
      account.jumpInfo = form.info;
    };
  }

  if (type.value == 2) {
    accountList.value.map((account: any) => {
      account.jumpInfo = form.info.map((jump_info: any) => jump_info.clone());
    })
  }
}

function getBackDisplay() {
  isH5.value && getCanvasPageOption();
  form.info = account.value.jumpInfo;
}
const formRef = ref();
const elementRef = ref();



function validate() {
  return new Promise<void>((resolve, reject) => {
    // console.log('Promise', 'Promise')
    if (!formRef.value) return resolve();
    formRef.value?.validate(async (errors: any) => {
      // console.log(errors, 'loaderr')
      if (!errors) {
        try {
          resolve()
        } catch (e) {
          reject();
          store.commit('adv/SCROLL_TO_ELEMENT', elementRef.value.$el)
        }
      } else {
        store.commit('adv/SCROLL_TO_ELEMENT', elementRef.value.$el)
        reject()
      }
    })
  })

}

defineExpose({
  getBackDisplay,
  validate
})




</script>
<style lang="scss">
.adv-load-page {
  .n-tabs .n-tabs-nav.n-tabs-nav--card-type .n-tabs-tab {
    background-color: #fff;
  }
}
</style>
<style lang="scss" scoped>
.search-box {
  //display: grid;
  //grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  //gap: 10px;
  margin-bottom: 10px;
}

.product-list {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 10px;
  max-height: 300px;

  .item {
    display: flex;
    border-radius: 6px;
    padding: 4px;
    cursor: pointer;
    border: 1px solid #ebeef5;

    &:hover {
      background-color: #f5f7fa;
    }

    &.selected {
      position: relative;
      background-color: #ffefee;

      &:after {
        content: '';
        position: absolute;
        right: 1px;
        bottom: 1px;
        width: 16px;
        height: 16px;
        background: linear-gradient(135deg, transparent 50%, #fa5a53 50%);
      }
    }

    .product-image {
      flex: none;
      width: 60px;
      height: 60px;
      border-radius: 4px;
      overflow: hidden;
      margin-right: 6px;

      .product-icon {
        font-size: 40px;
        line-height: 60px;
        color: #666666;
        text-align: center;
        display: block;
      }
    }

    .product-info {
      flex: 1;
      min-width: 120px;
      font-size: 12px;

      .sub-product {
        margin-top: 5px;
      }

      .product-text {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        line-height: 1.2em;

        &.light {
          color: #666666;
        }

        &.bold {
          font-weight: bold;
        }
      }
    }
  }
}
</style>
